<template>
  <div class="warp">
    <div class="btnBox">
      <div>
        <el-button type="primary" @click="submit" :loading="butloading"
          >开始解析</el-button
        >
        <el-button type="primary" @click="reset">重置</el-button>
      </div>
      <div>
        <el-button
          type="primary"
          @click="exportTable"
          :disabled="tableData.length == 0"
          >导出表格</el-button
        >
      </div>
    </div>
    <div>
      <el-input
        v-model="textarea"
        :rows="5"
        type="textarea"
        placeholder="请输入网址,用回车换行哦"
        class="textarea"
      />
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="550"
      v-if="tableData.length != 0"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="url" label="网址" />
      <el-table-column prop="title" label="title" />
      <el-table-column prop="h1" label="h1" />
      <el-table-column fixed="right" label="结果" width="120">
        <template #default="scope">
          <span v-if="scope.row.status == '成功'">成功</span>
          <span v-else>失败</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" v-if="tableData.length != 0">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :hideOnSinglePage="true"
        :pageSize="pageSize"
        :total="storeArray.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
  <!-- <div class="phrase" @click="refresh()">
    <p>
      {{ phrase[0] }}
    </p>
    <p class="phrtext">
      {{ phrase[1] }}
    </p>
  </div> -->
</template>

<script lang="ts">
import xlsx, { WorkSheet } from "xlsx";
import { defineComponent, ref, onMounted } from "vue";
import axios from "axios";
import { message } from "ant-design-vue";
import { phraselist } from "../until/phrase";
export default defineComponent({
  setup() {
    let tableData: any = ref([]);
    let tableHead: any = ref([]);
    let butloading = ref<boolean>(false);
    let phrase: any = ref([]);
    let pageSize: any = ref(20);
    let correctLenght: any = ref(0);
    let errorLength: any = ref(0);
    let storeArray: any = ref([]);
    let newArray: any = ref([]);
    let sum = 0;
    let datalist: any = [];
    const textarea = ref("");
    onMounted(() => {
      refresh();
    });
    const tableRowClassName = ({ row }: any) => {
      if (row.status == "成功") {
        return "success-row";
      } else if (row.status == "失败") {
        return "warning-row";
      }
      return "";
    };
    const refresh = () => {
      let number = random(0, phraselist.length);
      phrase.value = [];
      phraselist[number].forEach((e) => {
        phrase.value.push(e);
      });
    };
    const random = (min: any, max: any) => {
      return Math.floor(Math.random() * (max - min)) + min;
    };
    const reset = () => {
      textarea.value = "";
      sum = 0;
      tableData.value = [];
      storeArray.value = [];
    };
    const arrTrans = (num: any, arr: any) => {
      // 一维数组转换为二维数组
      let iconsArr: any = []; // 声明数组
      arr.forEach((item: any, index: any) => {
        const page = Math.floor(index / num); // 计算该元素为第几个素组内
        if (!iconsArr[page]) {
          // 判断是否存在
          iconsArr[page] = [];
        }
        iconsArr[page].push(item);
      });
      return iconsArr;
    };
    const submit = async () => {
      if (textarea.value == "") {
        message.error("请输入网址");
        return;
      }
      datalist = textarea.value.split("\n");
      sum = 0;
      tableData.value = [];
      storeArray.value = [];
      butloading.value = true;
      for (const fn of datalist) {
        await analysis(fn);
        setList();
      }
    };
    const analysis = async (e: any) => {
      let p1 = await getH1(e);
      await Promise.all([p1])
        .then((result: any) => {
          sum++;
          if (result[0].data.code == 0) {
            storeArray.value.push({
              url: result[0].data.data.Url,
              title: result[0].data.data.title,
              h1: result[0].data.data.h1,
              status: "成功",
            });
          } else {
            storeArray.value.push({
              url: e,
              title: result[0].data.msg,
              h1: result[0].data.msg,
              status: "失败",
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    };
    const setList = () => {
      if (sum == datalist.length) {
        butloading.value = false;
        newArray.value = arrTrans(pageSize.value, storeArray.value);
        tableData.value = newArray.value[0];
      }
    };
    const handleCurrentChange = (val: number) => {
      tableData.value = newArray.value[val - 1];
    };
    const getH1 = (url: any) => {
      return new Promise((resolve, reject) => {
        axios
          .get("/api/htmlInfo?url=" + url)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            message.error("服务器连接失败");
            reject(err);
          });
      });
    };
    const exportTable = () => {
      let aoa = [["网页地址", "title", "h1", "结果"]];
      tableData.value.forEach((e: any) => {
        aoa.push([e.url, e.title, e.h1, e.status]);
      });
      let worksheet: WorkSheet = xlsx.utils.aoa_to_sheet(aoa);
      let workbook = xlsx.utils.book_new();
      xlsx.utils.book_append_sheet(workbook, worksheet, "信息");
      xlsx.writeFile(workbook, "网页标题解析.xls");
    };
    return {
      tableHead,
      tableData,
      phrase,
      setList,
      correctLenght,
      storeArray,
      textarea,
      pageSize,
      newArray,
      tableRowClassName,
      errorLength,
      handleCurrentChange,
      refresh,
      reset,
      butloading,
      submit,
      exportTable,
    };
  },
});
</script>
<style>
body {
  background: url("../assets/background.svg");
}
</style>

<style lang="less" scoped>
.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
/deep/ .el-table .warning-row {
  color: red;
}
/deep/ .el-table .success-row {
  color: #606266;
}
.flexSpan {
  display: flex;
  align-items: center;
}
.phrase {
  position: absolute;
  left: 50px;
  top: 0px;
  padding-top: 80px;
  font-family: cursive;
  writing-mode: vertical-lr;
  font-size: 40px;
  opacity: 0.5;
  cursor: pointer;
}

.phrtext {
  margin-top: 50px;
}
.flexbox {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.el-table--border {
  background-color: rgba(0, 0, 0, 0);
}

/deep/ .el-table tr {
  background-color: rgba(0, 0, 0, 0);
}
.warp {
  margin: 0 auto;
  position: relative;
  z-index: 9;
}

.btnBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.textarea {
  /deep/ textarea {
    max-height: 400px;
  }
}
</style>
